/**
 * Licensed to Open-Ones Group under one or more contributor license
 * agreements. See the NOTICE file distributed with this work
 * for additional information regarding copyright ownership.
 * Open-Ones Group licenses this file to you under the Apache License,
 * Version 2.0 (the "License"); you may not use this file
 * except in compliance with the License. You may obtain a
 * copy of the License at:
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on
 * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package mks.webshop.gaedao;

import static java.lang.System.out;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;

import mks.webshop.common.AC;
import mks.webshop.dao.IMasterDao;
import mks.webshop.entity.BasePanel;
import mks.webshop.entity.Category;
import mks.webshop.entity.Counter;
import mks.webshop.entity.Logo;
import mks.webshop.entity.Notice;
import mks.webshop.entity.Order;
import mks.webshop.entity.OrderDetail;
import mks.webshop.entity.PanelType;
import mks.webshop.entity.Product;
import mks.webshop.entity.Tab;
import mks.webshop.entity.User;
import mks.webshop.entity.Food;
import mks.webshop.entity.OrderDetail;
import mks.webshop.entity.Order;
import openones.gaecore.PMF;

/**
 * @author thachle
 */
public class GAEMstDao extends GAEBaseMasterDao implements IMasterDao {
    final static Logger LOG = Logger.getLogger("GAEMasterDao");

    /**  Default language code: VN. */
    private String langCd = AC.VN;
    
    @Override
    public void setLangCd(String langCd) {
        this.langCd = langCd;
    }

    /**
     * Get all product categories level 1..
     * @return
     * @see mks.webshop.dao.IMasterDao#getCategoryList()
     */
    @Override
    public List<Category> getCategoryList() {
        PersistenceManager pm = PMF.get().getPersistenceManager();
        Query query = pm.newQuery(Category.class);
        String filter = "(lang == langCdParam) && (level == 1)";
        String parameter = "String langCdParam";

        query.setFilter(filter);
        query.declareParameters(parameter);

        List<Category> modList = (List<Category>) query.execute(this.langCd);
        if (modList != null){
        	return modList;
        }
        else{
        	return null;
        }
    }
    
    
    
    /**
     * Get all product categories ..
     * @return
     * @see mks.webshop.dao.IMasterDao#getAllCategoryList()
     */
    @Override
    public List<Category> getAllCategoryList() {
        PersistenceManager pm = PMF.get().getPersistenceManager();
        Query query = pm.newQuery(Category.class);
        String filter = "lang == langCdParam";
        String parameter = "String langCdParam";

        query.setFilter(filter);
        query.declareParameters(parameter);

        List<Category> modList = (List<Category>) query.execute(this.langCd);
        return modList;
    }
    
    /**
     * Get all saleoff product list  ..
     * @return
     * @see mks.webshop.dao.IMasterDao#getAllSaleOffProductList()
     */
    @Override
    public List<Product> getAllSaleOffProductList() {
        PersistenceManager pm = PMF.get().getPersistenceManager();
        Query query = pm.newQuery(Product.class);
        String filter = "(lang == langCdParam) && (price > 0)";
        String parameter = "String langCdParam";

        query.setFilter(filter);
        query.declareParameters(parameter);

        List<Product> modList = (List<Product>) query.execute(this.langCd);
        return modList;
    }
    
    /**
     * Get all product list  ..
     * @return
     * @see mks.webshop.dao.IMasterDao#getAllProductList()
     */
    @SuppressWarnings("unchecked")
	@Override
    public List<Product> getAllProductList() {
        PersistenceManager pm = PMF.get().getPersistenceManager();
        Query query = pm.newQuery(Product.class);
        String filter = "";
        String parameter = "";

        query.setFilter(filter);
        query.declareParameters(parameter);

        List<Product> modList = (List<Product>) query.execute();
        return modList;
    }
    
    /**
     * Get Logo ..
     * @return
     */
    @Override
    public Logo getLogo() {
        PersistenceManager pm = PMF.get().getPersistenceManager();
        Query query = pm.newQuery(Logo.class);
        String filter = "lang == langCdParam";
        String parameter = "String langCdParam";

        query.setFilter(filter);
        query.declareParameters(parameter);

        List<Logo> logo = (List<Logo>) query.execute(this.langCd);
        if ((logo != null) && (logo.size() == 1)){
        	return logo.get(0);
        }
        return null;
    }
    
    /**
     * Get amount subcategories ..
     * @return
     * @see mks.webshop.dao.IMasterDao#getAmountSubcategory()
     */
    public int getAmountSubcategory(String catId, int catLevel){
    	List<Category> modList = getSubCategoryList(catId, catLevel);
    	if ((modList != null) && (modList.size() > 0)) {
    		return modList.size();
    	} else {
    		return 0;
    	}
    }
    
    /**
     * Get amount subproduct ..
     * @return
     * @see mks.webshop.dao.IMasterDao#getAmountSubproduct()
     */
    public int getAmountSubproduct(String catId) {
    	List<Product> modList = getSubProductList(catId);
    	if ((modList != null) && (modList.size() > 0)) {
    		return modList.size();
    	} else {
    		return 0;
    	}
    }
    /**
     * [Explain the description for this method here].
     * Sub categories: Category has id start with "catId".
     * Ex: find sub categories of "ACB"
     * ACB1, ABC2
     * @param catId
     * @param level level of current category
     * @return
     * @see mks.webshop.dao.IMasterDao#getSubCategoryList(java.lang.String)
     */
    @Override
    public List<Category> getSubCategoryList(String catId, int level) {
        PersistenceManager pm = PMF.get().getPersistenceManager();
        Query query = pm.newQuery(Category.class);
        String filter = "(lang == langCdParam) && (id.startsWith(idParam)) && (level == levelParam)";
        String parameter = "String langCdParam, String idParam, int levelParam";
        query.setFilter(filter);
        query.declareParameters(parameter);
        List<Category> modList = (List<Category>) query.execute(this.langCd, catId, level + 1);
        if ((modList != null) && (modList.size() >= 1)) {
        	return modList;
        } else {
        	return null;
        }
    }
    
    /**
     * [Explain the description for this method here].
     * Sub categories: Category has id start with "catId".
     * Ex: find sub categories of "ACB"
     * ACB1, ABC2, ACB12, ACB123, ....
     * @param catId
     * @return
     * @see mks.webshop.dao.IMasterDao#getSubCategoryList(java.lang.String)
     */
    @Override
    public List<Category> getAllSubCategoryList(String catId) {
        PersistenceManager pm = PMF.get().getPersistenceManager();
        Query query = pm.newQuery(Category.class);
        String filter = "(lang == langCdParam) && (id.startsWith(idParam))";
        String parameter = "String langCdParam, String idParam";
        query.setFilter(filter);
        query.declareParameters(parameter);
        List<Category> modList = (List<Category>) query.execute(this.langCd, catId);
        if ((modList != null) && (modList.size() >= 1)) {
        	return modList;
        } else {
        	return null;
        }
    }
    
    
    /**
     * Lấy danh sách sản phẩm theo id của category
     * @param catId id của category cha chứa product
     * @see mks.webshop.dao.IMasterDao#getSubCategoryList(java.lang.String)
     */
    @Override
    public List<Product> getSubProductList(String catId) {
        PersistenceManager pm = PMF.get().getPersistenceManager();
        Query query = pm.newQuery(Product.class);
        String filter = "(lang == langCdParam) && (catId == catIdParam)";
        String parameter = "String langCdParam, String catIdParam";
        query.setFilter(filter);
        query.declareParameters(parameter);
        List<Product> modList = (List<Product>) query.execute(this.langCd, catId);
        if ((modList != null) && (modList.size() >= 1)) {
        	return modList;
        } else {
        	return null;
        }
    }
 
    /**
     * Lấy danh sách sản phẩm theo id của category sắp xếp theo tên sản phẩm
     * @param catId id của category cha chứa product
     * @see mks.webshop.dao.IMasterDao#getSubCategoryList(java.lang.String)
     */
    public List<Product> getSubProductListSortingName(String catId) {
        PersistenceManager pm = PMF.get().getPersistenceManager();
        Query query = pm.newQuery(Product.class);
        String filter = "(lang == langCdParam) && (catId == catIdParam)";
        String parameter = "String langCdParam, String catIdParam";
        query.setFilter(filter);
        query.declareParameters(parameter);
        query.setOrdering("name desc");
        List<Product> modList = (List<Product>) query.execute(this.langCd, catId);
        if ((modList != null) && (modList.size() >= 1)) {
        	return modList;
        } else {
        	return null;
        }
    }
    
    /// phuong thuc lay san pham theo so luong hien thi tren site
    public List<Product> getProductWithQuantity(List<Product> list, int quantity){
    	int size = list.size();
    	List<Product> results = new ArrayList<Product>();
    	if(size > quantity){   	
        	for(int index = 0; index < quantity; index ++){
        		results.add(list.get(size - index - 1));
        	}
        	return results;
    	}else{
    		results = inverseList(list);
        	return results;
    	}
    }
    
    /// phuong thuc sap xep lai thu tu san pham trong danh sach
    public List<Product> inverseList(List<Product> list){
    	int size = list.size();
    	List<Product> results = null;   
    	try{
    		if(size > 0){
    			results = new ArrayList<Product>();
    			for(int index = 0; index < size; index ++)
    	    		results.add(list.get(size - index - 1));
    		}	
    	}catch(Exception e){
    		e.printStackTrace();
    	}
    	return results;
    }
    
    /**
     * Lay danh sach cac category theo thu tu (tu category cha den cac category con tuong ung de den category hien tai)
     * @param catId id va level cua category hien tai
     * @see mks.webshop.dao.IMasterDao#getParentCategoryList(java.lang.String)
     */
    public List<Category> getParentCategoryList (String catId, int level){
    	List<Category> modList = new ArrayList<Category>();
    	for (int i = 0; i < level; i++){
    		LOG.finest("List parent id" + catId.substring(0, i + 1));
    		modList.add(i, getCategoryById(catId.substring(0, i + 1)));
    	}
    	return modList;
    }
    
   

    
    @Override
    public boolean deleteCatByKey(Long key) {
    	return PMF.delete(key, Category.class);
    }
    
    @Override
    public boolean deleteUserByKey(Long key) {
    	return PMF.delete(key, User.class);
    }
           
    @Override
    public boolean deleteProByKey(Long key){
    	return PMF.delete(key, Product.class);
    }
    
    @Override
    public boolean deleteOrderByKey(Long key){
    	return PMF.delete(key, Order.class);
    }
    @Override
    public boolean deleteSubProByCat(Category cat) {
    	List<Product> modProList =  getSubProductList(cat.getId());
    	if ((modProList != null) && (modProList.size() > 0)) {
	    	for (Product pro:modProList) {
	    		PMF.delete(pro.getKey(), Product.class);
	    	}
	    	return true;
    	} else {
    		return false;
    	}
    }
    
    @Override
    public boolean deleteSubCatByCat(Category cat) {
    	List<Category> modCatList = getSubCategoryList(cat.getId(), cat.getLevel());
    	if ((modCatList != null) && (modCatList.size() > 0)) {
    		for (Category cat1:modCatList) {
    			PMF.delete(cat1.getKey(), Category.class);
    		}
    		return true;
    	} else {
    		return false;
    	}
 
    }

    /**
     * [Explain the description for this method here].
     * @param id
     * @return true: success; false: there is no category or found above 1 category.
     * @see mks.webshop.dao.IMasterDao#deleteCatById(java.lang.String)
     * Step 1: Lookup project category by id.
     * Step 2: Delete looked category by key.
     */
    @Override
    public boolean deleteCatById(String id) {
        PersistenceManager pm = PMF.get().getPersistenceManager();
        Query query = pm.newQuery(Category.class);
        String filter = "(lang == langCdParam) && (id == idParam)";
        String parameter = "String langCdParam, String idParam";

        query.setFilter(filter);
        query.declareParameters(parameter);
        List<Category> cat = (List<Category>) query.execute(this.langCd, id);
        
        if ((cat != null) && (cat.size() == 1)) {
            PMF.delete(cat.get(0).getKey(), Category.class);
            return true;
        } else {
            return false;
        }
    }
    
    /**
     * [Explain the description for this method here].
     * @param cat
     * @return
     * @see mks.webshop.dao.IMasterDao#save(com.google.appengine.api.datastore.Category)
     */
    
    @Override
    public boolean saveCat(Category cat) {
        cat.setLang(this.langCd);  
//        return super.save(cat);
        Category cat1 = new Category();
        cat1 = getCategoryById(cat.getId());
        if (cat1 == null) { // Save newly
            return super.save(cat);
        } else { // Update
            PersistenceManager pm = PMF.get().getPersistenceManager();
            try {
                Category existedCat = pm.getObjectById(Category.class, cat1.getKey());
                existedCat.setName(cat.getName());
                existedCat.setImageKey(cat.getImageKey());                
                return true;
            } finally {
                pm.close();
            }
        }

    }
    
    @Override
    public boolean isExistedCat(String id) {
    	PersistenceManager pm = PMF.get().getPersistenceManager();
        Query query = pm.newQuery(Category.class);
        String filter = "(lang == langCdParam) && (id == idParam)";
        String parameter = "String langCdParam, String idParam";

        query.setFilter(filter);
        query.declareParameters(parameter);
        List<Category> modList = (List<Category>) query.execute(this.langCd, id);
        if ((modList != null) && (modList.size() > 0)){
        	return true;      
        }
        return false;
    }
    
    
    @Override
    public boolean isExistedPro(String id) {
    	PersistenceManager pm = PMF.get().getPersistenceManager();
    	Query query = pm.newQuery(Product.class);
    	String filter = "(lang == langCdParam) && (id == idParam)";
    	String parameter = "String langCdParam, String idParam";
    	
    	query.setFilter(filter);
    	query.declareParameters(parameter);
    	List<Product> modList = (List<Product>) query.execute(this.langCd, id);
    	if ((modList != null) && (modList.size() > 0)){
    		return true;
    	}
    	return false;
    }
    
    
    @Override
    public List<Product> getProductList() {
        PersistenceManager pm = PMF.get().getPersistenceManager();
        Query query = pm.newQuery(Product.class);
        String filter = "lang == langCdParam";
        String parameter = "String langCdParam";

        query.setFilter(filter);
        query.declareParameters(parameter);

        List<Product> modList = (List<Product>) query.execute(this.langCd);

        return modList;
    }

    @Override
    public boolean saveProduct(Product product) {
        product.setLang(this.langCd); 
        Product pro = new Product();
        pro = getProductById(product.getId());
        if (pro == null) { // Save newly
            return super.save(product);
        } else { // Update
            PersistenceManager pm = PMF.get().getPersistenceManager();
            try {
                Product existedPro = pm.getObjectById(Product.class, pro.getKey());
                existedPro.setName(product.getName());
                existedPro.setId(product.getId());
                existedPro.setPrice(product.getPrice());
                existedPro.setInfo(product.getInfo());
                existedPro.setDescription(product.getDescription());
                existedPro.setNewPrice(product.getNewPrice());
                existedPro.setUnit(product.getUnit());
                existedPro.setQuantity(product.getQuantity());
//                existedPro.setImageKey(product.getImageKey());
//                existedPro.setLargeImageKey(product.getLargeImageKey());
                return true;
            } finally {
                pm.close();
            }
        }
    }
    
    @Override
    public boolean saveProductImage(Product product) {
        product.setLang(this.langCd); 
        Product pro = new Product();
        pro = getProductById(product.getId());
        PersistenceManager pm = PMF.get().getPersistenceManager();
        try {
              Product existedPro = pm.getObjectById(Product.class, pro.getKey());            
              existedPro.setImageKey(product.getImageKey());
//                existedPro.setLargeImageKey(product.getLargeImageKey());
              return true;
        }finally {
              pm.close();
        }
    }

    /* 
	 * Lấy product theo id
	 * @return trả về đối tượng product
     * @see mks.webshop.dao.IMasterDao#getProductById(java.lang.String)
     * 
     */
    @Override
    public Product getProductById(String proId){
    	PersistenceManager pm = PMF.get().getPersistenceManager();
        Query query = pm.newQuery(Product.class);
        String filter = "(lang == langCdParam) && (id == idParam)";
        String parameter = "String langCdParam, String idParam";
        query.setFilter(filter);
        query.declareParameters(parameter);
        List<Product> proList = (List<Product>) query.execute(this.langCd, proId);
        if ((proList != null) && (proList.size() == 1)){
        	 return proList.get(0);      
        }
        return null;
    }
    
    /**
     * Get sub categories.
     * @param id
     * @param lay chinh xac category theo id
     * @return
     * @see mks.webshop.dao.IMasterDao#getCategoryById(java.lang.String, boolean)
     */
    @Override
    public Category getCategoryById(String id) {
        PersistenceManager pm = PMF.get().getPersistenceManager();
        Query query = pm.newQuery(Category.class);
        String filter = "(lang == langCdParam) && (id == idParam)";
        String parameter = "String langCdParam, String idParam";

        query.setFilter(filter);
        query.declareParameters(parameter);
        List<Category> modList = (List<Category>) query.execute(this.langCd, id);
        if ((modList != null) && (modList.size() == 1)){
        	return modList.get(0);      
        }
        return null;
    }

    @Override
    public List<Tab> getTabList() {
        PersistenceManager pm = PMF.get().getPersistenceManager();
        String ordering = "orderNo asc";

        List<Tab> tabList = (List<Tab>) PMF.getObjects(Tab.class, PMF.NO_FILTER, PMF.NO_IMPORT, PMF.NO_PARAM, ordering,
                PMF.NO_PARAMVALUE);

        return tabList;
    }

    @Override
    public boolean saveTab(Tab tab) {
        return super.save(tab);
    }

    @Override
    public boolean deleteTabById(String tabId) {
        return PMF.deleteById(tabId, Tab.class);
    }

    @Override
    public boolean deleteTabByKey(Long key) {
        return PMF.delete(key, Tab.class);
    }

    /**
     * Save/Update the panel.
     * @param panel
     * If panel.key is already existed, the updating is performed.
     * @return
     * @see mks.webshop.dao.IMasterDao#savePanel(mks.webshop.entity.BasePanel)
     */
    @Override
    public boolean savePanel(BasePanel panel) {
        panel.setLang(this.langCd);
        
        if (panel.getKey() == null) { // Save newly
            return super.save(panel);
        } else { // Update
            PersistenceManager pm = PMF.get().getPersistenceManager();
            try {
                BasePanel existedPanel = pm.getObjectById(BasePanel.class, panel.getKey());
                existedPanel.setContent(panel.getContent());
                
                return true;
            } finally {
                pm.close();
            }
        }
    }
    
    @Override
    public boolean saveLogo(Logo logo) {
        logo.setLang(this.langCd);
        Logo existedLogo1 = getLogo();
        if (existedLogo1 == null) { // Save newly
            return super.save(logo);
        } else { // Update
        	LOG.finest("Update");
        	 PersistenceManager pm = PMF.get().getPersistenceManager();
        	 try {
                Logo existedLogo = pm.getObjectById(Logo.class, existedLogo1.getKey());
                existedLogo.setImageKey(logo.getImageKey());
                return true;
        	 }
               
                finally {
                    pm.close();
                }
       }
        
    }
    
    @Override
    public Category getCategoryId(String id) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public BasePanel getPanel(PanelType type) {
        PersistenceManager pm = PMF.get().getPersistenceManager();
        Query query = pm.newQuery(BasePanel.class);
        String filter = "(lang == langCdParam) && (type == typeParam)";
        String parameter = "String langCdParam, PanelType typeParam";

        query.setFilter(filter);
        query.declareParameters(parameter);
        List<BasePanel> panelList = (List<BasePanel>) query.execute(this.langCd, type);
        
        return (panelList.isEmpty() ? null : panelList.get(0));
    }

    @Override
    public List<BasePanel> getAllPanels() {
        PersistenceManager pm = PMF.get().getPersistenceManager();
        Query query = pm.newQuery(BasePanel.class);
        String filter = "(lang == langCdParam)";
        String parameter = "String langCdParam";

        query.setFilter(filter);
        query.declareParameters(parameter);
        List<BasePanel> panelList = (List<BasePanel>) query.execute(this.langCd);
        
        return panelList;
    }
    
    @Override
    public Notice getNoticeById(String id){
    	PersistenceManager pm = PMF.get().getPersistenceManager();
        Query query = pm.newQuery(Notice.class);
        String filter = "(lang == langCdParam) && (id == idParam)";
        String parameter = "String langCdParam, String idParam";
        query.setFilter(filter);
        query.declareParameters(parameter);
        List<Notice> noticeList = (List<Notice>) query.execute(this.langCd, id);
        if ((noticeList != null) && (noticeList.size() == 1)){
        	 return noticeList.get(0);      
        }
        return null;
    }
    
    @Override
    public boolean saveNotice(Notice note) {
        note.setLang(this.langCd); 
        Notice modNote = new Notice();
        modNote = getNoticeById(note.getId());
        if (modNote == null) { // Save newly
            return super.save(note);
        } else { // Update
            PersistenceManager pm = PMF.get().getPersistenceManager();
            try {
                Notice existedNote = pm.getObjectById(Notice.class, modNote.getKey());
                existedNote.setName(note.getName());
                existedNote.setId(note.getId());
                existedNote.setDescription(note.getDescription());
                return true;
            } finally {
                pm.close();
            }
        }
    }
    
    @Override
    public boolean deleteNoticeByKey(Long key){
    	return PMF.delete(key, Notice.class);
    }
    
    @Override
    public List<Notice> getAllNoticeList() {
        PersistenceManager pm = PMF.get().getPersistenceManager();
        Query query = pm.newQuery(Notice.class);
        String filter = "lang == langCdParam";
        String parameter = "String langCdParam";

        query.setFilter(filter);
        query.declareParameters(parameter);
//        query.setOrdering("created desc");
        List<Notice> modList = (List<Notice>) query.execute(this.langCd);
        if ((modList != null) && (modList.size() >= 1)) {
        	return modList;
        } else {
        	return null;
        }
    }
    
    public List<Notice> getNoticeWithQuantity(List<Notice> list, int quantity){
    	int size = list.size();
    	List<Notice> results = new ArrayList<Notice>();
    	if(size > quantity){   	
        	for(int index = 0; index < quantity; index ++){
        		results.add(list.get(size - index - 1));
        	}
        	return results;
    	}else{
    		results = inverseNoticeList(list);
        	return results;
    	}
    }
    
    public List<Notice> inverseNoticeList(List<Notice> list){
    	int size = list.size();
    	List<Notice> results = null;   
    	try{
    		if(size > 0){
    			results = new ArrayList<Notice>();
    			for(int index = 0; index < size; index ++)
    	    		results.add(list.get(size - index - 1));
    		}	
    	}catch(Exception e){
    		e.printStackTrace();
    	}
    	return results;
    }
    
    @Override
    public boolean saveUser(User user) {
        user.setLang(this.langCd); 
        User tempUser = new User();
        tempUser = getUserById(user.getId());
        if (tempUser == null) { // Save newly
            return super.save(user);
        } else { // Update
            PersistenceManager pm = PMF.get().getPersistenceManager();
            try {
                User existedUser = pm.getObjectById(User.class, tempUser.getKey());
                if(!user.getName().equals("")){
                	existedUser.setName(user.getName());
                }
                if(!user.getId().equals("")){
                	existedUser.setId(user.getId());
                }
                if(!user.getPassword().equals("")){
                	 existedUser.setPassword(user.getPassword());
                }
                if(!user.getEmail().equals("")){
                	existedUser.setEmail(user.getEmail());
                }
                if(!user.getPhonenumber().equals("")){
                	existedUser.setPhonenumber(user.getPhonenumber());
                }
                if(!user.getDeliveryNo().equals("")){
                	existedUser.setDeliveryNo(user.getDeliveryNo());
                }
                if(!user.getDeliveryStreet().equals("")){
                	existedUser.setDeliveryStreet(user.getDeliveryStreet());
                }
                if(!user.getDeliveryWard().equals("")){
                	existedUser.setDeliveryWard(user.getDeliveryStreet());
                }
                if(!user.getDeliveryDistrict().equals("")){
                	existedUser.setDeliveryDistrict(user.getDeliveryStreet());
                }  
                return true;
            } finally {
                pm.close();
            }
        }
    }
    
    
    
    @Override
    public User getUserById(String id){
    	PersistenceManager pm = PMF.get().getPersistenceManager();
        Query query = pm.newQuery(User.class);
        String filter = "(lang == langCdParam) && (id == idParam)";
        String parameter = "String langCdParam, String idParam";
        query.setFilter(filter);
        query.declareParameters(parameter);
        List<User> userList = (List<User>) query.execute(this.langCd, id);
        if ((userList != null) && (userList.size() == 1)){
        	 return userList.get(0);      
        }
        return null;
    }
    
	 /// Cài đặt cho service lớp Food
	@Override
	public boolean saveFood(Food food) {
		try{
			food.setLang(this.langCd);
			Food foodChecking = getFoodByCode(food.getCode());
			if(foodChecking == null){
				super.save(food);
				return true;
			}
			else{
				PersistenceManager pm = PMF.get().getPersistenceManager();
				Food foodModify =  pm.getObjectById(Food.class, foodChecking.getKey());
				foodModify.setName(food.getName());
				foodModify.setCode(food.getCode());
				foodModify.setDetail(food.getDetail());
				pm.close();
				return true;
			}
		}catch(Exception e){
			e.printStackTrace();
			return false;
		} 
	}

	@Override
	public boolean deleteFood(long id) {
		
		return PMF.delete(id, Food.class);
	}

	@SuppressWarnings("unchecked")
	@Override
	public Food getFoodByCode(String code) {
		try{
			PersistenceManager pm = PMF.get().getPersistenceManager();
			Query query = pm.newQuery(Food.class);
			String filter = "(lang == langCdParam) && (code == codeParam)";
	        String parameter = "String langCdParam, String codeParam";
	        query.setFilter(filter);
	        query.declareParameters(parameter); 	        
			List<Food> results = (List<Food>) query.execute(this.langCd, code);
	        if (results != null && results.size() > 0){
	        	 return results.get(0);     
	        }
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
        return null;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<Food> getAllFoodList() {
		try{
			PersistenceManager pm = PMF.get().getPersistenceManager();
			Query query = pm.newQuery(Food.class);
			String filter = "(lang == langCdParam)";
	        String parameter = "String langCdParam";
	        query.setFilter(filter);
	        query.declareParameters(parameter);
//	        query.setOrdering("created desc");
			List<Food> results = (List<Food>) query.execute(this.langCd);
	        if (results != null && results.size() > 0){
	        	 return results;    
	        }
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
        return null;
	}

	@Override
	public boolean saveFoodImage(Food food) {
		food.setLang(this.langCd); 
        Food foodObject = new Food();
        foodObject = getFoodByCode(food.getCode());
        PersistenceManager pm = PMF.get().getPersistenceManager();
        try {
              Food existedFood = pm.getObjectById(Food.class, foodObject.getKey());            
              existedFood.setImageKey(food.getImageKey());
              return true;
        }finally {
              pm.close();
        }
	}

	@Override
	public List<Food> getFoodWithQuantity(List<Food> list, int quantity) {
		int size = list.size();
    	List<Food> results = new ArrayList<Food>();
    	if(size > quantity){   	
        	for(int index = 0; index < quantity; index ++){
        		results.add(list.get(size - index - 1));
        	}
        	return results;
    	}else{
    		results = inverseFoodList(list);
        	return results;
    	}
	}

	@Override
	public List<Food> inverseFoodList(List<Food> list) {
		int size = list.size();
    	List<Food> results = null;   
    	try{
    		if(size > 0){
    			results = new ArrayList<Food>();
    			for(int index = 0; index < size; index ++)
    	    		results.add(list.get(size - index - 1));
    		}	
    	}catch(Exception e){
    		e.printStackTrace();
    	}
    	return results;
	}
	
	
	//khong tim duoc tieng viet
	@Override
	public List<Product> getListProductByName(String name){
		PersistenceManager pm = PMF.get().getPersistenceManager();
        Query query = pm.newQuery(Product.class);
        char[] stringArray = name.toCharArray();
        stringArray[0] = Character.toUpperCase(stringArray[0]);
        name = new String(stringArray);
        String filter = "(lang == langCdParam) && (name.startsWith(nameParam))";
        String parameter = "String langCdParam, String nameParam";
        query.setFilter(filter);
        query.declareParameters(parameter);
//	   	System.out.print("test name " + name);
        List<Product> proList = (List<Product>) query.execute(this.langCd, name);
        if (proList != null){
        	 return proList;      
        }else{
        	return null;
        }
        
	}
	
	@Override
	public boolean saveOrder(Order order) {	
		try {
			
				super.save(order);
				return true;
			
		} catch (Exception e) {
			e.printStackTrace();
			
		}
		return false;
	}

	@Override
	public boolean setIsDone(Order order, boolean isDone) {
		
		System.out.print(order.getKey());
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {			
			Order orderModify =  pm.getObjectById(Order.class, order.getKey());
			orderModify.setIsDone(isDone);
			pm.close();
			return true;
		} catch (Exception e) {
			pm.close();
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public boolean setProductIsSpecial(Product pro, int isSpecial) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try{
			Product modPro = pm.getObjectById(Product.class, pro.getKey());
			modPro.setIsSpecial(isSpecial);
			pm.close();
			return true;
		} catch (Exception e) {
			pm.close();
			e.printStackTrace();
		}
		return false;
		}
	
	@SuppressWarnings("unchecked")
	@Override
	public Order getOrderByCode(String code) {
		try{
			PersistenceManager pm = PMF.get().getPersistenceManager();
			Query query = pm.newQuery(Order.class);
			String filter = "(code == codeParam)";
	        String parameter = "String codeParam";
	        query.setFilter(filter);
	        query.declareParameters(parameter); 	        
			List<Order> results = (List<Order>) query.execute(code);
	        if (results != null && results.size() > 0){
	        	 return results.get(0);    
	        }
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
        return null;
	}

	@Override
	public boolean saveOrderDetail(OrderDetail detail) {
		try {
			super.save(detail);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
		}		
		return false;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<OrderDetail>  getOrderDetailByOrderCode(String code) {
		try{
			PersistenceManager pm = PMF.get().getPersistenceManager();
			Query query = pm.newQuery(OrderDetail.class);
			String filter = "(orderCode == codeParam)";
	        String parameter = "String codeParam";
	        query.setFilter(filter);
	        query.declareParameters(parameter); 	        
			List<OrderDetail> results = (List<OrderDetail>) query.execute(code);
	        if (results != null && results.size() > 0){
	        	 return results;     
	        }
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
        return null;
	}

	@Override
	public long getMaxOrderKey() {
		try {
			List<Order> list = getAllOrder();
			System.out.print(list.size());
			if(list.size() == 0)
				return list.size();
			else
			{
				String lastCode = (list.get(list.size()-1)).getCode();
				long max = Long.parseLong(lastCode.substring(8));
				System.out.print(max);
				return max;
			}
		} catch (Exception e) {
			return 0;
		}
	
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Order> getAllOrder() {
		
		try{
			PersistenceManager pm = PMF.get().getPersistenceManager();
			Query query = pm.newQuery(Order.class);   
			String filter = "";
	        String parameter = "";
	        query.setFilter(filter);
	        query.declareParameters(parameter);
			List<Order> results = (List<Order>) query.execute();
	        if (results != null){
	        	 return results;     
	        }
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
        return null;
	}

	@Override
	public List<Order> getOrdersByState(boolean isDone) {
		try{
			PersistenceManager pm = PMF.get().getPersistenceManager();
			Query query = pm.newQuery(Order.class);
			String filter = "(isDone == isDoneParam)";
	        String parameter = "String isDoneParam";
	        query.setFilter(filter);
	        query.declareParameters(parameter); 	        
			List<Order> results = (List<Order>) query.execute(isDone);
	        if (results != null){
	        	System.out.print(results.size());
	        	 return results;     
	        }
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
        return null;
	}
	@SuppressWarnings("unchecked")
	@Override
	public boolean checkLogin(String username, String password) {
		
		try{
			PersistenceManager pm = PMF.get().getPersistenceManager();
			Query query = pm.newQuery(User.class);   
			String filter = "(id == idParam) && (password == passwordParam)";
	        String parameter = "String idParam, String passwordParam";
	        query.setFilter(filter);
	        query.declareParameters(parameter); 
			List<Order> results = (List<Order>) query.execute(username, password);
	        if (results != null && results.size() > 0){
	        	 return true;     
	        }
		}catch(Exception e){
			e.printStackTrace();
			return false;
		}
       
		return false;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<User> getAllUser() {
		
		try{
			PersistenceManager pm = PMF.get().getPersistenceManager();
			Query query = pm.newQuery(User.class);   
			List<User> results = (List<User>) query.execute();
	        if (results != null && results.size() > 0){
	        	 return results;     
	        }
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
        return null;
	}

	@Override
	public long computeBasePrice(List<OrderDetail> list) {
		long result = 0;
		for (OrderDetail orderDetail : list) {
			result += orderDetail.getPrice();
		}
		return result;
	}

	@Override
	public boolean save(Counter counter, int increament) {
		try{		
			Counter count = getCounter();
			if(count == null){
				counter.setCount(new Long(0));
				super.save(counter);
				return true;
			}
			else{
				PersistenceManager pm = PMF.get().getPersistenceManager();
				Counter counterModify =  pm.getObjectById(Counter.class, count.getKey());
				long sequence = count.getCount();
				counterModify.setCount(sequence + increament);
				pm.close();
				return true;
			}
		}catch(Exception e){
			e.printStackTrace();
			return false;
		} 
	}

	@SuppressWarnings("unchecked")
	@Override
	public Counter getCounter() {
		try{
			PersistenceManager pm = PMF.get().getPersistenceManager();
			Query query = pm.newQuery(Counter.class);   
			String filter = "";
	        String parameter = "";
	        query.setFilter(filter);
	        query.declareParameters(parameter);
			List<Counter> results = (List<Counter>) query.execute();
	        if (results != null && results.size() > 0){
	        	 return results.get(0);     
	        }
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
        return null;
	}
}
